package com.yuan.blog.exception;

import com.yuan.blog.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * @program: blog
 * @description:
 * @author: yuan_boss
 * @create: 2022-12-19 11:02
 **/

@ControllerAdvice
@Slf4j
public class BlogExceptionHandler {

    // 系统异常，Exception一行
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public R systemException(Exception e) {
        log.error(this.getClass() + ": 系统异常:" + e.getMessage());
        return R.error("系统正在维护，请联系管理员");
    }

    // 业务异常，BaseException包括子类
    @ExceptionHandler(BaseException.class)
    @ResponseBody
    public R baseException(BaseException e) {
        log.error(e.getMsg(), e);
        return R.error(e.getMsg()).put("code",e.getCode());
    }


    @ExceptionHandler(JsonException.class)
    @ResponseBody
//    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public R JsonException(JsonException e){
        log.warn(this.getClass() + ": 操作异常");
        return R.error(e.getCode(),e.getMsg());
    }

    @ExceptionHandler(ViewException.class)
//    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ModelAndView ViewException(ViewException e){
        log.warn(this.getClass() + ": 返回页面");
        ModelAndView mv = new ModelAndView();
        mv.setViewName("view/error/404.html");
        mv.addObject("msg",e.getMsg());
        return mv;
    }

}
